package com.heima.comment.service.Impl;

import com.heima.apis.user.SelectUser;
import com.heima.comment.service.CommentService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.CommentConstants;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GreenTextScan textScan;

    /*@Autowired
    private IArticleClients iArticleClients;*/

    @Autowired
    private SelectUser iUserClient;

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentSaveDto dto, HttpServletRequest request) {
        //校验参数
        if (StringUtils.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //评论表对象
        ApComment apComment = new ApComment();
        //评论内容不能超过140个字
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(501, "评论字数过多");
        }
        //敏感词扫描
        Boolean scanComment = scanComment(dto.getContent());
        if (!scanComment) {
            return ResponseResult.errorResult(512, "评论检测不通过");
        }
        //通过Feign调用根据文章id拿到文章表信息
        //ApArticle apArticle = iArticleClients.selectArticle(dto.getArticleId());

        //存入评论表
        //通过feign接口根据用户id拿到用户名字
        String userId = request.getHeader("userId");
        if("0".equals(userId) ){
            return ResponseResult.errorResult(505,"请登录后在评论");
        }
        ApUser apUser = iUserClient.selectUser(Integer.parseInt(userId));
        apComment.setAuthorName(apUser.getName());
        apComment.setAuthorId(Integer.parseInt(userId));

       /* apComment.setAuthorName("admin");
        apComment.setAuthorId(4);*/

        apComment.setFlag(0);
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setOperation(null);
        apComment.setEntryId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private Boolean scanComment(String content) {
        boolean flag = true;
        try {
            Map map = textScan.greeTextScan(content);
            String suggestion = map.get("suggestion") + "";
            if ("block".equals(suggestion)) {
                flag = false;
            } else if ("review".equals(suggestion)) {
                flag = false;
            }
        } catch (Exception e) {
            log.error("文本扫描异常", e);
        }
        return flag;
    }

    /**
     * 加载评论列表
     *
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        //校验参数
        if (StringUtils.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //校验分页参数
        dto.checkParam();


        Date minDate = dto.getMinDate();
        //Date minDate = new Date(1640966400000L);

        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                        .and("createdTime").lt(minDate))
                        .skip(dto.getSize()*(dto.getIndex()-1))
                        .limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);

        //ResponseResult result = new PageResponseResult(dto.getIndex(), dto.getSize(), apComments.size());

        //result.setData(apComments);
        return ResponseResult.okResult(apComments);
    }

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto,HttpServletRequest request) {
        //校验参数
        if (StringUtils.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //拿到用户id
        String userId = request.getHeader("userId");

        //根据评论id拿到评论数据中的点赞数
        String commentId = dto.getCommentId();
        ApComment apComment = mongoTemplate.findById(commentId, ApComment.class);

        if (dto.getOperation() == CommentConstants.LIKE) {
            apComment.setLikes(apComment.getLikes() + 1);
            apComment.setOperation(0);

            //点赞存入点赞表
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(commentId);
            apCommentLike.setAuthorId(Integer.parseInt(userId));

            mongoTemplate.save(apComment);
            mongoTemplate.save(apCommentLike);
        } else if (dto.getOperation() == CommentConstants.NOT_LIKE) {
            apComment.setLikes(apComment.getLikes() - 1);
            apComment.setOperation(null);
            mongoTemplate.save(apComment);

            //取消点赞就删除记录
            Query query = Query.query(Criteria.where("commentId").is(commentId).and("authorId").is(4));
            mongoTemplate.remove(query,ApCommentLike.class);
        }
        return ResponseResult.okResult(apComment);
    }
}
